package com.dc.di.ftpserver.database;

import java.io.File;
import java.util.Date;

import org.apache.log4j.Logger;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.util.UUIDUtil;

import com.dc.di.ftpserver.entity.AttachmentlogEntity;
import com.dc.di.ftpserver.logmanager.SendLog;
import com.dc.di.ftpserver.util.Const;

public class AttachmentSendDbLog implements SendLog{
	private AttachmentLogManager aLogManager;
	private static final Logger logger = Logger.getLogger(AttachmentSendDbLog.class);
	public AttachmentSendDbLog()throws KettleException {
		this.aLogManager=AttachmentLogManager.getSendInstance();
	}
	@Override
	public void saveSendLog(String[] parameter,File file)throws Exception{		
		String filename=file.getName();
		String filepath=file.getAbsolutePath();
		String groupname=parameter[1];
		String groupsn=parameter[2];
		filepath = filepath.substring(0,filepath.lastIndexOf(filename));
		if(aLogManager.getDataId(groupname, filename, filepath)==null){
			AttachmentlogEntity attachLog = new AttachmentlogEntity();
			attachLog.setId(UUIDUtil.getUUIDAsString());
			attachLog.setGroupname(groupname);
			attachLog.setGroupsn(groupsn);
			attachLog.setFilename(filename);
			attachLog.setFilesize(file.length());
			attachLog.setFilepath(filepath);
			attachLog.setStarttime(new Date());
			attachLog.setFlag(Const.FLAG_START);
			aLogManager.insertSendLog(attachLog);
		}else{
			if(logger.isDebugEnabled()){
				logger.debug(new StringBuilder("the attachmentsendlog is exist:").append("groupname=").append(groupname)
						.append(",filename=").append(filename).append(",filepath=").append(filepath));
			}
		}
	}
	public void updateSendLog(String groupname,File file,String Flag) throws Exception{
		AttachmentlogEntity attachLog = new AttachmentlogEntity();
		String filename=file.getName();
		String filepath=file.getAbsolutePath();
		filepath = filepath.substring(0,filepath.lastIndexOf(filename));
		attachLog.setGroupname(groupname);
		attachLog.setFilename(filename);
		attachLog.setFilepath(filepath);
		attachLog.setEndtime(new Date());
		attachLog.setFilesize(file.length());
		attachLog.setFlag(Const.FLAG_END);
		aLogManager.updatelog(attachLog);
	}
	@Override
	public void updateSendSuccessLog(String groupname,File file) throws Exception{
		updateSendLog(groupname,file,Const.FLAG_END);
	}
	@Override
	public void updateSendFailLog(String groupname,File file) throws Exception{
		updateSendLog(groupname,file,Const.FLAG_FAIL);
	}
}
